package org.jeecg.modules.cxf;

import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.interceptor.AbstractLoggingInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.io.DelegatingInputStream;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.Phase;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.logging.Logger;

/**
 * @Description
 * @Author linminfeng
 * @Date 2020-11-07 15:41
 */
public class WsInterceptor extends AbstractLoggingInterceptor {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(WsInterceptor.class);

    public WsInterceptor() {
        super(Phase.RECEIVE);
    }

    @Override
    protected Logger getLogger() {
        return null;
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        InputStream is = message.getContent(InputStream.class);
        if (is != null) {
            CachedOutputStream bos = new CachedOutputStream();
            if (threshold > 0) {
                bos.setThreshold(threshold);
            }
            try {
                // 使用适当的输入流并在以后还原
                InputStream bis = is instanceof DelegatingInputStream ? ((DelegatingInputStream) is).getInputStream() : is;

                //仅复制到最大限制，因为这就是我们需要记录的全部
                //我们可以流剩下的
                IOUtils.copyAtLeast(bis, bos, limit == -1 ? Integer.MAX_VALUE : limit);
                bos.flush();
                bis = new SequenceInputStream(bos.getInputStream(), bis);

                // 恢复委托输入流或输入流
                if (is instanceof DelegatingInputStream) {
                    ((DelegatingInputStream) is).setInputStream(bis);
                } else {
                    message.setContent(InputStream.class, bis);
                }

                bos.close();
            } catch (IOException e) {
                throw new Fault(e);
            } finally {
                LOGGER.info(bos.toString());
            }
        }
    }
}
